﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : Page
{
    private string error_msg;
    protected void Page_Load(object sender, EventArgs e)
    {
        //页面加载前先检查是否用户在本机登录，这里只需检查userID
        //如果已经登录则重定向到
        if (Request.Cookies["userID"] != null)
        {
            //利用JS倒计时并重定向
            notification.InnerHtml = "<p class=\"login\">你已经以 " + Request.Cookies["username"].Value + "的身份登录了</p>" +
                                     "<p>您可以<a href=\"logout.aspx\">切换账户</a></p>" +
                                     "<p id=\"countDown\"></p>" +
                                     "<script>var a = 1;</script>" +
                                     "<script src=\"js/jquery-1.9.1.js\"></script>" +
                                     "<script src=\"js/jquery.cookie.js\"></script>" +
                                     "<script src=\"js/congratulations.js\"></script>";
            //将表单设置为不可见
            form_container.Visible = false;
        }
    }

    protected void submit_Click(object sender, EventArgs e)
    {
        if (username.Text.Trim() == string.Empty)
        {
            error_msg = "请输入用户名";
            notification.InnerHtml = error_msg;
            return;
        }
        else if (password.Text.Trim() == string.Empty)
        {
            error_msg = "请输入密码";
            notification.InnerHtml = error_msg;
            return;
        }
        else
        {
            //预处理用户名
            string username_worked = username.Text.Trim();

            //预处理密码
            byte[] password_worked = SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(password.Text.Trim()));
                
            //从配置文件读取连接字符串
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionString"];

            //建立数据库连接
            using (SqlConnection databaseConnection = new SqlConnection(settings.ConnectionString))
            {
                databaseConnection.Open();

                //构建查询语句，检查用户登录信息
                string queryString = "SELECT userID, username " +
                                     "FROM users " +
                                     "WHERE username = @username AND password = @password";

                SqlCommand command = new SqlCommand(queryString, databaseConnection);

                SqlParameter usernameSqlParameter = new SqlParameter("@username", username_worked);
                SqlParameter passwordSqlParameter = new SqlParameter("@password", password_worked);
                command.Parameters.AddRange(new SqlParameter[]{usernameSqlParameter, passwordSqlParameter});

                SqlDataReader reader;
                try
                {
                    reader = command.ExecuteReader();
                }
                catch (Exception exception)
                {
                    error_msg = "数据库方面发生了错误，请点击页脚的“联系我们”告知我们，我们会尽快修复 AFTER LOGIN " + exception.Message;
                    notification.InnerHtml = error_msg;
                    return;
                }

                //查找到登录信息，登录成功，设置Cookie，重定向到欢迎页面
                if (reader.HasRows)
                {
                    reader.Read();
                    Response.Cookies.Add(new HttpCookie("userID", reader["userID"].ToString()));
                    Response.Cookies.Add(new HttpCookie("username", reader["username"].ToString()));

                    //检查用户密保功能状态，以决定是否显示指向passwordProtection页面的链接
                    queryString = "SELECT * " +
                                  "FROM PasswordProtection " +
                                  "WHERE userID = @userID";
                    command.CommandText = queryString;
                    command.Parameters.Clear();
                    SqlParameter userIDParameter = new SqlParameter("@userID", reader["userID"].ToString());
                    reader.Close();
                    command.Parameters.Add(userIDParameter);
                    try
                    {
                        reader = command.ExecuteReader();
                    }
                    catch (Exception exception)
                    {
                        error_msg = "数据库方面发生了错误，请联系我们以解决 AFTER CHECK PasswordProtection STATUS " + exception.Message;
                        notification.InnerHtml = error_msg;
                        return;
                    }

                    if (!reader.HasRows)
                    {
                        Response.Cookies.Add(new HttpCookie("passwordProtectionStatus", "1"));
                        //1代表没有密保问题也没有邮箱
                    }
                    else
                    {
                        reader.Read();
                        if (!Convert.ToBoolean(reader["Verified"]))
                        {
                            Response.Cookies.Add(new HttpCookie("passwordProtectionStatus", "2"));
                            //2号代表有密保问题但是没有通过邮箱验证
                        }
                    }
                    reader.Close();
                    Response.Redirect("congratulations.html");
                }
                else
                {
                    error_msg = "您所输入的用户名或密码错误，请检查后重新输入";
                    notification.InnerHtml = error_msg;
                    return;
                }
                databaseConnection.Close();
            }
        }
    }
}